package fr.sportcom.sportcom.controller;

import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import fr.sportcom.sportcom.R;
import fr.sportcom.sportcom.SportComApplication;
import fr.sportcom.sportcom.model.AdsManager;
import fr.sportcom.sportcom.model.CustomHttpClient;
import fr.sportcom.sportcom.model.User;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class CreateUserActivity extends FragmentActivity
implements DatePickerDialog.OnDateSetListener {


	//// EXTRA
	// En entr�e :
	public final static String EXTRA_ACTION = "fr.sportcom.sportcom.extra.cua.ACTION";
	public final static String EXTRA_USER = "fr.sportcom.sportcom.extra.cua.USER";

	// Valeur d'ACCTION:
	public final static int CREAT = 1, READ = 2, EDIT = 3;

	// DatePicker
	DialogFragment mDatePicker = new DatePickerFragment();

	// Parametre
	private int pAction;
	private User pUser;

	// Variable de valeur.
	private String mEmail;
	private String mPassword;
	private String mConfirm;
	private String mFirstName;
	private String mLastName;
	private int mDateDay = 0;
	private int mDateMonth = 0;
	private int mDateYear = 0;
	private String mCity;

	// UI references.
	private EditText mEmailView;
	private EditText mPassView;
	private EditText mConfView;
	private EditText mFNameView;
	private EditText mLNameView;
	private Button   mDateView;
	private Button   mApplyView;
	private EditText mCityView;

	private UserCreatTask mRegTask;

	public static Intent prepareIntent(Context context, int action, User user) {
		return new Intent(context, CreateUserActivity.class)
		.putExtra(EXTRA_ACTION, action)
		.putExtra(EXTRA_USER, user);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_create_user);
		setContentView(R.layout.sponso_layout);
		View appContent = LayoutInflater.from(this).inflate(
				R.layout.activity_create_user, 
				(ViewGroup) this.findViewById(R.id.app_content), 
				false);
		((LinearLayout)this.findViewById(R.id.app_content)).addView(appContent);
		AdsManager.displayAds(this);

		((DatePickerFragment) mDatePicker).linkListener(this);

		mEmailView = (EditText) findViewById(R.id.email);
		mPassView  = (EditText) findViewById(R.id.password);
		mConfView  = (EditText) findViewById(R.id.conf);
		mFNameView = (EditText) findViewById(R.id.first_name);
		mLNameView = (EditText) findViewById(R.id.last_name);
		mDateView  = (Button) findViewById(R.id.btn_pick_date);
		mCityView  = (EditText) findViewById(R.id.city);
		mApplyView = (Button) findViewById(R.id.create_user_button);

		mDateView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mDatePicker.show(getSupportFragmentManager(), "datePicker");
			}
		});

		mApplyView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				attemptCreate();
			}
		});
		

		// On recupere les parametre
		Intent i = getIntent();
		pAction = i.getIntExtra(EXTRA_ACTION, 1);
		pUser = i.getParcelableExtra(EXTRA_USER);
		if(pUser == null) {
			pUser = ((SportComApplication) (this.getApplication())).getLoggedUser();
		}
		DateFormat FormatDate = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE);
		switch(pAction){
		case CREAT :
			findViewById(R.id.ads_lay).setVisibility(View.GONE);
			break;
		case READ :
			//pUser = i.getParcelableExtra(EXTRA_USER);
			mEmailView.setText(pUser.getMail());
			mEmailView.setEnabled(false);
			((LinearLayout) findViewById(R.id.grp_pass)).setVisibility(View.GONE);
			((LinearLayout) findViewById(R.id.grp_conf)).setVisibility(View.GONE);
			mFNameView.setText(pUser.getFirstName());
			mFNameView.setEnabled(false);
			mLNameView.setText(pUser.getLastName());
			mLNameView.setEnabled(false);
			mDateView.setText(""+pUser.getAge());
			mDateView.setEnabled(false);
			mCityView.setText(pUser.getCity());
			mCityView.setEnabled(false);
			mApplyView.setVisibility(View.GONE);
			break;
		case EDIT :
			pUser = ((SportComApplication) (this.getApplication())).getLoggedUser();
			mEmailView.setText(pUser.getMail());
			mFNameView.setText(pUser.getFirstName());
			mLNameView.setText(pUser.getLastName());
			mDateView.setText(FormatDate.format(pUser.getBorn()));
			pUser.getBorn(mDateYear, mDateMonth, mDateDay);
			mCityView.setText(pUser.getCity());
			break;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		AdsManager.displayAds(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create_user, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			//NavUtils.navigateUpFromSameTask(this);
			this.finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void attemptCreate() {
		if (mRegTask != null) {
			return;
		}

		// Reset errors.
		mEmailView.setError(null);
		mPassView.setError(null);
		mConfView.setError(null);
		mFNameView.setError(null);
		mLNameView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPassView.getText().toString();
		mConfirm = mConfView.getText().toString();
		mFirstName = mFNameView.getText().toString();
		mLastName = mLNameView.getText().toString();
		mCity = mCityView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid confirmation password.
		if (TextUtils.isEmpty(mLastName)) {
			mLNameView.setError(getString(R.string.error_field_required));
			focusView = mLNameView;
			cancel = true;
		}

		// Check for a valid confirmation password.
		if (TextUtils.isEmpty(mFirstName)) {
			mFNameView.setError(getString(R.string.error_field_required));
			focusView = mFNameView;
			cancel = true;
		}

		// Check for a valid confirmation password.
		if (TextUtils.isEmpty(mConfirm)) {
			mConfView.setError(getString(R.string.error_field_required));
			focusView = mConfView;
			cancel = true;
		} else if (mConfirm.compareTo(mPassword) != 0) {
			mConfView.setError(getString(R.string.error_invalid_confirmation));
			focusView = mConfView;
			cancel = true;
		}

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPassView.setError(getString(R.string.error_field_required));
			focusView = mPassView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPassView.setError(getString(R.string.error_invalid_password));
			focusView = mPassView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			//mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			//showProgress(true);
			mRegTask = new UserCreatTask();
			mRegTask.link(this);
			mRegTask.execute();
		}
	}

	private class UserCreatTask extends AsyncTask<Void, Void, Boolean> {

		private WeakReference<CreateUserActivity> mActivity = null;

		@Override
		protected Boolean doInBackground(Void... params) {

			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("uti_email", mEmail));
			param.add(new BasicNameValuePair("uti_motDePasse", User.hashSha256(mPassword)));
			param.add(new BasicNameValuePair("uti_prenom", mFirstName));
			param.add(new BasicNameValuePair("uti_nom", mLastName));
			String temp = String.format("%04d", mDateYear)
					+ "-" + String.format("%02d", mDateMonth)
					+ "-" + String.format("%02d", mDateDay);
			param.add(new BasicNameValuePair("uti_naissance", temp));
			param.add(new BasicNameValuePair("uti_ville", mCity));

			try {
				//Thread.sleep(5000);
				jObj = request.postData("createUser", param);

				if(jObj.getInt("back") != 0) {
					return false;
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mRegTask = null;

			if (!success) {
				Toast.makeText(mActivity.get(), "Une erreur est survenue.", Toast.LENGTH_LONG).show();
				return;
			}

			finish();
		}

		public void link (CreateUserActivity pActivity) {
			mActivity = new WeakReference<CreateUserActivity>(pActivity);
		}
	}


	public static class DatePickerFragment extends DialogFragment {
		private WeakReference<DatePickerDialog.OnDateSetListener> mActivity;

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), mActivity.get(), year, month, day);
		}

		public void linkListener(DatePickerDialog.OnDateSetListener c) {
			mActivity = new WeakReference<DatePickerDialog.OnDateSetListener>(c);
		}
	}

	@Override
	public void onDateSet(DatePicker view, int year, int month, int day) {
		mDateDay = day;
		mDateMonth = month +1;
		mDateYear = year;

		mDateView.setText(String.format("%02d", mDateDay) 
				+ "/" + String.format("%02d", mDateMonth) 
				+ "/" + String.format("%04d", mDateYear));
	}
}
